import bcrypt from 'bcrypt'
import mongoose from 'mongoose'
import { Note } from '../models/note.js'


async function getNotesList (req, res) {
  // 没有登录 去登录
  if (!req.session.user || Object.keys(req.session.user).length === 0) {
    return res.render("login")
  }
  let { title } = req.body
  // 构建查询条件
  let query = {
    user_id: req.session.user.id
  }
  if (title) {
    // 使用 MongoDB 的 $regex 运算符实现模糊查询，'i' 表示不区分大小写
    query.title = { $regex: title, $options: 'i' }
  }
  console.log('query', query)
  // 查找数据库中符合条件的笔记
  const notes = await Note.find(query).lean() || []
  // 此处不考虑分页, 前端可做成虚拟列表形式
  res.render("list-notes", { count: notes.length, notes })
}

async function addNotes (req, res) {
  // 没有登录 去登录
  if (!req.session.user || Object.keys(req.session.user).length === 0) {
    return res.render("login")
  }
  const { title, content, week, weather, tag } = req.body
  console.log('add req body', req.body)
  const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0')
  const id = `1120${ randomNum }`
  if (!title) {
    return res.render("add-note", { titleError: true })
  }
  await Note.create({ user_id: req.session.user.id, id, title, content, tag, week, weather })
  res.redirect("/list-all-notes")
}

async function delNotes (req, res) {
  // 没有登录 去登录
  if (!req.session.user || Object.keys(req.session.user).length === 0) {
    return res.render("login")
  }

  const { id } = req.body
  try {
    const delNote = await Note.findOneAndDelete({ id, user_id: req.session.user.id }).exec()
    if (!delNote) {
      throw new Error('删除失败!')
    }
    return res.status(200).json({ msg: 'OK', code: 0 })
  } catch (error) {
    console.error(error)
    // 处理错误响应
    res.status(500).json({ msg: error.message, code: 1 })
  }
}

async function updNotes (req, res) {
  // 检查用户是否已登录
  if (!req.session.user || Object.keys(req.session.user).length === 0) {
    return res.render("login")
  }
  console.log('updNotes:', req.body)
  try {
    const { id, title, content, week, weather, tag } = req.body
    console.log('upd req body', req.body)
    // 更新笔记
    const updatedNote = await Note.findByIdAndUpdate(
      id,
      { title, content, week, weather, tag, user_id: req.session.user.id },
      { new: true, runValidators: true }
    )

    if (!updatedNote) {
      throw new Error('更新失败!')
    }
    // 更新成功
    const notes = await Note.find({ user_id: req.session.user.id }).lean() || []
    // 此处不考虑分页, 前端可做成虚拟列表形式
    res.render("list-notes", { count: notes.length, notes })
  } catch (error) {
    console.error(error)
    // 处理错误响应
    res.status(500).json({ msg: error.message, code: 1 })
  }
}
// 收藏
async function collectnotes (req, res) {
  if (!req.session.user || Object.keys(req.session.user).length === 0) {
    return res.render("login")
  }
  console.log(req.body)
  try {
    const { id, collect } = req.body
    console.log(id, collect);
    // 更新笔记
    const updatedNote = await Note.findOneAndUpdate(
      { id: id },
      { collect },
      { new: true, runValidators: true }
    )

    if (!updatedNote) {
      throw new Error('收藏成功!')
    }
    return res.status(200).json({ msg: 'OK', code: 0 })
  } catch (error) {
    console.error(error)
    // 处理错误响应
    res.status(500).json({ msg: error.message, code: 1 })
  }
}
// 查看我的收藏
async function myCollectNoteList (req, res) {
  if (!req.session.user || Object.keys(req.session.user).length === 0) {
    return res.render("login")
  }
  try {
    const notesList = await Note.find({ collect: true, user_id: req.session.user.id }).lean() || []
    res.render("collect-notes", { notes: notesList })
  } catch (error) {
    console.log(error)
  }
}
// 获取笔记详情
async function getNoteDetail (req, res, id) {
  // 检查用户是否已登录
  if (!req.session.user || Object.keys(req.session.user).length === 0) {
    return res.render("login")
  }
  try {
    const note = await Note.findOne({ id }).lean()
    if (!note) {
      return res.status(404).json({ msg: '未找到笔记' })
    }

    res.render('upd-note', { note })
  } catch (error) {
    console.error(error)
    res.status(500).json({ msg: '服务器错误' })
  }
}

export default {
  getNotesList, addNotes, delNotes, updNotes, getNoteDetail, collectnotes, myCollectNoteList
}